package com.chinairi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinairi.common.annotation.DoPage;
//import com.chinairi.mall.config.RunDemo;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.config.ValidationResult;
import com.chinairi.mall.config.ValidatorImpl;
import com.chinairi.mall.controller.viewobject.ApproveDbIdVO;
import com.chinairi.mall.controller.viewobject.GoodsPictureVO;
import com.chinairi.mall.controller.viewobject.ServiceShelfVO;
import com.chinairi.mall.dao.GoodsPictureMapper;
import com.chinairi.mall.dao.ServiceShelfPriceAddMapper;
import com.chinairi.mall.dao.ServiceShelfPriceMultiMapper;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.model.*;
import com.chinairi.mall.dao.ServiceShelfMapper;
import com.chinairi.mall.service.IServiceShelfService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.mall.service.modelobject.HomeGoodsMO;
import com.chinairi.mall.service.modelobject.HomeServiceMO;
import com.chinairi.mall.service.modelobject.ServiceTypeShopMO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 五大服务上架功能以及服务商对服务的维护功能， 服务实现类
 * </p>
 *
 * @author Webgasd
 * @since 2020-09-16
 */
@Service
public class ServiceShelfServiceImpl extends ServiceImpl<ServiceShelfMapper, ServiceShelf> implements IServiceShelfService {
    @Autowired
    private ServiceShelfMapper serviceShelfMapper;
    @Autowired
    private ServiceShelfPriceMultiMapper serviceShelfPriceMultiMapper;
    @Autowired
    private ServiceShelfPriceAddMapper serviceShelfPriceAddMapper;
    @Autowired
    private ValidatorImpl validator;
    @Autowired
    private GoodsPictureMapper goodsPictureMapper;

    /**
     * 根据店铺主键获取店铺中的服务产品信息
     *
     * @param serviceShelf 店铺主键
     * @return list
     */
    @Override
    @DoPage
    public List<ServiceShelf> getListByCsDbId(ServiceShelf serviceShelf) {
        return serviceShelfMapper.getListByCsDbId(serviceShelf);
    }

    /**
     * 根据主键获取具体服务商品信息
     *
     * @param serviceDbId 主键
     * @return ServiceShelfVO
     */
    @Override
    public ServiceShelfVO getByDbId(String serviceDbId) {
        ServiceShelf result = serviceShelfMapper.selectById(serviceDbId);
        if (result == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "不存在此条目，请检查后重试");
        }
        ServiceShelfVO serviceShelfVO = new ServiceShelfVO();
        BeanUtils.copyProperties(result, serviceShelfVO);
        Map<String, Object> map = new HashMap<>(1);
        map.put("SERVICE_DBID", serviceDbId);
        List<ServiceShelfPriceMulti> serviceShelfPriceMultiList = serviceShelfPriceMultiMapper.selectByMap(map);
        List<ServiceShelfPriceAdd> serviceShelfPriceAddList = serviceShelfPriceAddMapper.selectByMap(map);
        serviceShelfVO.setServiceShelfPriceMultiList(serviceShelfPriceMultiList);
        serviceShelfVO.setServiceShelfPriceAddList(serviceShelfPriceAddList);
        return serviceShelfVO;
    }

    /**
     * 添加服务商品
     *
     * @param serviceShelfVO 服务商品详情
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ServiceShelfVO serviceShelfVO) {

        ValidationResult result = validator.validate(serviceShelfVO);
        if (result.isHashErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, result.getErrMsg());
        }

        String serviceDbid = UUID.randomUUID().toString().replace("-", "");
        serviceShelfVO.setServiceDbid(serviceDbid);
        serviceShelfVO.setSsStatus(0);
        /*
        这里后续添加审批流
         */
        serviceShelfVO.setSsApproveState(0);
        serviceShelfMapper.insert(serviceShelfVO);
        batchDelete(serviceDbid);
        batchInsertMulti(serviceShelfVO.getServiceShelfPriceMultiList(), serviceDbid);
        batchInsertAdd(serviceShelfVO.getServiceShelfPriceAddList(), serviceDbid);
    }

    /**
     * 更新服务商品信息
     *
     * @param serviceShelfVO 服务商品信息
     */
    @Override
    public void updateAll(ServiceShelfVO serviceShelfVO) {
        ValidationResult result = validator.validate(serviceShelfVO);
        if (result.isHashErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, result.getErrMsg());
        }
        serviceShelfVO.setSsStatus(0);
        serviceShelfVO.setSsApproveState(0);
        serviceShelfMapper.updateById(serviceShelfVO);
        batchDelete(serviceShelfVO.getServiceDbid());
        batchInsertMulti(serviceShelfVO.getServiceShelfPriceMultiList(), serviceShelfVO.getServiceDbid());
        batchInsertAdd(serviceShelfVO.getServiceShelfPriceAddList(), serviceShelfVO.getServiceDbid());
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(String id) {
        //删除乘性表
        QueryWrapper<ServiceShelfPriceMulti> wrapper1 = new QueryWrapper<>();
        wrapper1
                .eq("SERVICE_DBID", id);
        serviceShelfPriceMultiMapper.delete(wrapper1);
        //删除加性表
        QueryWrapper<ServiceShelfPriceAdd> wrapper2 = new QueryWrapper<>();
        wrapper2
                .eq("SERVICE_DBID", id);
        serviceShelfPriceAddMapper.delete(wrapper2);
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchInsertMulti(List<ServiceShelfPriceMulti> serviceShelfPriceMultiList, String serviceDbid) {
        if (serviceShelfPriceMultiList.size() > 0) {
            serviceShelfPriceMultiMapper.batchInsert(serviceShelfPriceMultiList.stream().peek(list -> {
                list.setSpDbid(list.getSpDbid() == null ? UUID.randomUUID().toString().replace("-", "") : list.getSpDbid());
                list.setServiceDbid(serviceDbid);
            }).collect(Collectors.toList()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchInsertAdd(List<ServiceShelfPriceAdd> serviceShelfPriceAddList, String serviceDbid) {
        if (serviceShelfPriceAddList.size() > 0) {
            serviceShelfPriceAddMapper.batchInsert(serviceShelfPriceAddList.stream().peek(list -> {
                list.setSspDbid(list.getSspDbid() == null ? UUID.randomUUID().toString().replace("-", "") : list.getSspDbid());
                list.setServiceDbid(serviceDbid);
            }).collect(Collectors.toList()));
        }
    }

    @Override
    public Map<String, List<ServiceTypeShopMO>> getMap(String serviceType, String serviceClass) {
        List<String> csDbIdList = serviceShelfMapper.getCsDbIdListByServiceType(serviceType, serviceClass);
        if (csDbIdList.size() == 0) {
            return null;
        }
        Map<String, List<ServiceTypeShopMO>> resultMap = new HashMap<>(csDbIdList.size());
        for (String csDbId : csDbIdList) {
            resultMap.put(csDbId, new ArrayList<ServiceTypeShopMO>());
        }
        List<ServiceTypeShopMO> serviceTypeShopMOList = serviceShelfMapper.getServiceInfoListByCsDbIdList(csDbIdList);
        if (serviceTypeShopMOList.size() == 0) {
            return resultMap;
        }
        for (ServiceTypeShopMO serviceTypeShopMO : serviceTypeShopMOList) {
            resultMap.get(serviceTypeShopMO.getCsDbid()).add(serviceTypeShopMO);
        }
        return resultMap;
    }

    /**
     * 批量提交商品审核
     *
     * @param approveDbIdVoList
     */
    @Override
    public void updateStatus(List<ApproveDbIdVO> approveDbIdVoList) {
        //获取前端传来的特征值对象
        if (approveDbIdVoList.size() > 0) {
            List<ServiceShelf> serviceShelfList = new ArrayList<>();
            for (ApproveDbIdVO approveDbIdVo : approveDbIdVoList) {
                ServiceShelf serviceShelf = new ServiceShelf();
                serviceShelf.setServiceDbid(approveDbIdVo.getDbId());
                if (approveDbIdVo.getType() == 1) {
                    serviceShelf.setSsStatus(1);
                } else if (approveDbIdVo.getType() == 3) {
                    serviceShelf.setSsStatus(3);
                }
                serviceShelf.setSsApproveState(3);

                serviceShelfList.add(serviceShelf);
            }
            //批量插入特征值
            serviceShelfMapper.batchUpdateStatus(serviceShelfList);
        }
    }

    /**
     * 服务商品搜索列表
     * 搜索项
     * csDbid               精确搜索   店铺id
     * ssServiceTypeDbid    精确搜索   服务大类编码
     * ssServiceTypeName    模糊搜索   服务大类名称
     * ssServiceClassDbid   精确搜索   服务小类编码
     * ssServiceClassName   模糊搜索   服务小类名称
     *
     * @param homeServiceMo
     * @return
     */
    @Override
    @DoPage
    public List<HomeServiceMO>
    getHomeService(HomeServiceMO homeServiceMo) {
        List<HomeServiceMO> homeServiceMOList = serviceShelfMapper.selectHomeService(homeServiceMo, UserSession.getUserId());
        List<String> serviceDbIdList = new ArrayList<>();
        for (HomeServiceMO homeServiceMO : homeServiceMOList) {
            serviceDbIdList.add(homeServiceMO.getServiceDbid());
        }
        List<GoodsPicture> goodsPictureList = goodsPictureMapper.selectByServiceIdList(serviceDbIdList);
        Map<String,List<GoodsPicture>> servicePicListMap = new HashMap<>(goodsPictureList.size());
        for (GoodsPicture goodsPicture : goodsPictureList) {
            servicePicListMap.put(goodsPicture.getGoodsDbid(),new ArrayList<>());
        }
        for (GoodsPicture goodsPicture : goodsPictureList) {
            servicePicListMap.get(goodsPicture.getGoodsDbid()).add(goodsPicture);
        }
        for(HomeServiceMO homeServiceMO : homeServiceMOList){
            homeServiceMO.setGoodsPictureList(servicePicListMap.get(homeServiceMO.getServiceDbid()));
        }
        return homeServiceMOList;
    }

    /**
     * 获取店铺服务列表
     *
     * @param serviceShelf
     * @return
     */
    @Override
    @DoPage
    public List<ServiceShelf> getServiceListByCsDbId(ServiceShelf serviceShelf) {
        return serviceShelfMapper.getServiceListByCsDbId(serviceShelf);
    }

    /**
     * 删除服务
     *
     * @param serviceDbid
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String serviceDbid) {
        serviceShelfMapper.deleteById(serviceDbid);
    }

    /**
     * 获取用户须知
     * @param serviceType 服务大类id
     * @param serviceClassIds 服务小类id
     */
    @Override
    public List<ServiceShelf> getNoticeByCsId(String serviceType, List<String> serviceClassIds) {
        return serviceShelfMapper.getNoticeByCsId(serviceType,serviceClassIds);
    }

    /**
     * 获取用户须知
     * @param serviceType 服务大类id
     * @param serviceClassIds 服务小类id
     */
    @Override
    public List<ServiceShelf> getPriceRuleByCsId(String serviceType, List<String> serviceClassIds) {
        return serviceShelfMapper.getPriceRuleByCsId(serviceType,serviceClassIds);
    }
}
